♞ Minimum Knight Moves using BFS

An interactive tutorial to find the shortest path on an infinite board.

Problem Statement (BFS Introduction)

Beginning from location (0,0), what is the minimum number of steps needed for a knight to get to some other arbitrary location (x,y)?

Constraints: $1 \le x, y \le 8$

Why BFS?

This problem asks for the **minimum number of steps**, which immediately suggests a **Breadth-First Search (BFS)**.

Knight's Move Set (The 8 Possible Jumps)

A knight moves in an 'L' shape: 2 squares in one direction (horizontal or vertical) and 1 square in the perpendicular direction. From $(0, 0)$, the possible moves are:

(1, 2)
(-1, 2)
(1, -2)
(-1, -2)
(2, 1)
(-2, 1)
(2, -1)
(-2, -1)

The BFS Algorithm Steps

Data Structures Needed

  • **Queue:** Stores the positions to visit. Each element is `(x, y, steps)`.
  • **Visited Set/Map:** Stores all `(x, y)` locations already processed to prevent cycles and redundant work. This is crucial for an infinite board.

Detailed Steps

  1. **Initialization:** Add the starting position $\mathbf{(0, 0)}$ with $\mathbf{0}$ steps to the Queue and mark it as visited.
  2. **Loop:** While the Queue is not empty, dequeue the front position $\mathbf{(x_c, y_c, s_c)}$.
  3. **Check Goal:** If $\mathbf{(x_c, y_c)}$ is the target $\mathbf{(x, y)}$, return $\mathbf{s_c}$.
  4. **Generate Next Moves:** Iterate through the 8 possible Knight moves (dx, dy). Calculate the new position $\mathbf{(x_n, y_n)}$.
  5. **Enqueue and Mark:** If $\mathbf{(x_n, y_n)}$ has not been visited, mark it as visited and enqueue $\mathbf{(x_n, y_n, s_c + 1)}$.

Algorithm Complexity

For a general graph, Time is $O(V + E)$ (Vertices + Edges). On a chessboard, we can approximate the search space to be the area reachable within the minimum number of steps $M$.

Time: $O(x \cdot y)$ or $O(M^2)$ (approximated search space)

Space: $O(x \cdot y)$ (for the Visited Set and Queue)

Interactive BFS Demo (Start at 0, 0)

Search Status

Waiting for target coordinates...

BFS Queue (Next to Visit)

Queue is empty.

Code Snippet (Main Loop)

function bfs() {
    // Queue stores {x, y, steps}
    while (queue.length > 0) {
        let {x, y, steps} = queue.shift();
        if (x === targetX && y === targetY) {
            return steps; // Found shortest path!
        }
        
        // Explore 8 moves
        for (let i = 0; i < 8; i++) {
            let nextX = x + DX[i];
            let nextY = y + DY[i];
            let key = `${nextX},${nextY}`;

            if (!visited.has(key)) {
                visited.add(key);
                queue.push({x: nextX, y: nextY, steps: steps + 1});
            }
        }
    }
}